<template>
  <section>
    <table cellspacing="0" cellpadding="0" border="0" class="table-container el-table table-info">
      <thead>
        <tr>
          <th colspan="3">
            <div>设备基本信息</div>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>设备总数: {{deviceTotalInfo.deviceCount}}</td>
          <td>激活设备: {{deviceTotalInfo.acCount}}</td>
          <td>当前在线: {{deviceTotalInfo.onlineCount}}</td>
        </tr>
      </tbody>
    </table>
    <el-row type="flex" justify="space-between" class="button-box">
      <el-col :span="12" class="left">
        <el-select v-model="activeProductId" placeholder="请选择产品" :disabled="disabled">
          <el-option v-for="(product, index) in productList" :label="product.name" :key="index" :value="product.id"></el-option>
        </el-select>
        <el-input placeholder="请输入DeviceName" class="search-input" v-model="params.search">
          <el-button slot="append" @click="searchDevice">搜索</el-button>
        </el-input>
      </el-col>
      <el-col :span="12" class="right">
        <el-button type="danger" @click="multipleSelectionChange('delete')">批量删除</el-button>
        <el-button type="info" @click="multipleSelectionChange('disable')">批量禁用</el-button>
        <el-button type="success" @click="multipleSelectionChange('enable')">批量启用</el-button>
        <el-button type="primary" @click="addDevice">添加设备</el-button>
      </el-col>
    </el-row>
    <device-table :listLoading="listLoading" :tableColumn="tableColumn" :tableData="tableData" :currentPage="currentPage" :total="total" :multipleFlag="multipleFlag" @handleSelectionChange="handleSelectionChange" @actionClick="actionClick" :buttonGroup="buttonGroup"
      @changeSwitch="changeSwitch" :pageSize="pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
      <template slot="nodeType" slot-scope="scope">
        <span>{{ scope.row.nodeType | nodeTypeFilter }}</span>
      </template>
      <template slot="status" slot-scope="scope">
        <span>{{ scope.row.status | deviceStatusFilter }}</span>
      </template>
      <template slot="lastime" slot-scope="scope">
        <span>{{ scope.row.lastime | crtimeFilter }}</span>
      </template>
      <!-- <template slot="status" slot-scope="scope">
        <div>
          {{ scope.row.status ? "激活" : "未激活" }}
          <el-switch v-model="scope.row.status" active-color="#409eff" inactive-color="#dcdfe6"  @change="changeSwitch(scope.row)">
          </el-switch>
        </div>
      </template> -->
    </device-table>

    <device-template :form="form" :productList="productList" :tip="tip" :title="formTitle" :dialogVisible.sync="dialogVisible"  @submitForm="submitForm" :disabled="disabled"></device-template>
  </section>
</template>

<script>
  import utilMixin from '@views/mixin/systemUtil'
  import DeviceTable from '@components/Table'
  import DeviceTemplate from '@views/device/components/DeviceTemplate'
  import { getDeviceList, addDevice, getDeviceDetail, updateDevice, updateDeviceStatus, deleteDevice, getDeviceTotalInfo } from '@api/device'
  import { getProductList } from '@api/product'
  import { Vue, Component, Watch } from 'vue-property-decorator'

  @Component({
    components: {
      DeviceTable,
      DeviceTemplate
    },
    mixins: [utilMixin]
  })
  export default class DeviceIndex extends Vue {
    data() {
      return {
        activeProductId: null, //当前激活的产品ID
        deviceTotalInfo: {}, //设备总数信息
        dialogVisible: false, //form表单是否显示
        productList: [], //产品列表
        formTitle: "", //表单title
        submitIndex: 0, //表单确定按钮回调索引 0新增 1查看 2编辑 3删除
        disabled: false, //表单元素是否可编辑
        form: {}, //form表单提交对象
        tip: "特别说明：deviceName可以为空,当为空时,阿里云会颁发全局唯一标识符作为deviceName。", //表单tip
        tableColumn: [ //表格列对象
          { type: "name", name: "DeviceName", operate: false },
          { type: "productName", name: "设备所属产品", operate: false },
          { type: "nodeType", name: "节点类型", operate: true },
          { type: "mac", name: "mac地址", operate: false },
          { type: "status", name: "设备状态", operate: true },
          { type: "lastime", name: "最后上线时间", operate: true }
        ],
        tableData: [], //表格数据
        multipleFlag: true, //是否支持多选
        multipleSelection: [], //多选数组
        currentPage: 1, //当前页码
        buttonGroup: [{ name: '查看' }, { name: '编辑' }, { name: '删除' }] //表格按钮数组
      }
    }
    @Watch('pageSize')
    pageSizeChange(val) { //监听一页数量
      this.params.limit = val;
      this.fetchData();
    }
    @Watch('pageIndex')
    pageIndexChange(val) { //监听页码索引
      this.currentPage = val - 0 + 1;
      this.params.offset = this.startOffsetNum;
      this.fetchData();
    }
    @Watch('activeProductId')
    activeProductIdChange(val) { //监听当前产品ID
      this.params.productId = val;
      this.pageIndex = 0;
      this.fetchData();
      this.initDeviceTotalInfo();
    }
    mounted() {
      this.params.offset = this.startOffsetNum;
      this.params.limit = this.pageSize;

      this.$nextTick(function() {
        this.initProductList();
      })
    }
    fetchData() { //初始化表格数据
      this.listLoading = true
      getDeviceList(this.params).then(response => {
        let res = response.data;
        if (res.status) {
          this.tableData = res.data.rows;
          this.total = res.data.total;
          this.listLoading = false;
        } else {
          this.showMessage(res.message, 'error');
        }
      })
    }
    initDeviceTotalInfo() { //初始化产品状态总数
      let params = {
        productId: this.params.productId
      }
      getDeviceTotalInfo(params).then(response => {
        let res = response.data;
        if (res.status) {
          this.deviceTotalInfo = res.data;
        } else {
          this.showMessage(res.message, 'error');
        }
      })
    }
    initProductList() { //初始化产品列表数据
      let params = {
        offset: 0,
        limit: 50
      }
      getProductList(params).then(response => {
        let res = response.data;
        if (res.status) {
          this.productList = res.data.rows;
          if (this.productList.length) {
            if (!this.activeProductId) {
              this.activeProductId = this.productList[0].id;
            }
          }
        } else {
          this.showMessage(res.message, 'error');
        }
      })
    }
    addDevice() { //新增设备
      this.commonEdit({}, 0);
    }
    actionClick(rowData, index) { //表单按钮组回调方法
      //1查看 2删除
      switch (index) {
        case 1:
          this.queryClick(rowData)
          break;
        case 2:
          this.editClick(rowData)
          break;
        case 3:
          this.deleteClick(rowData)
          break;
      }
    }
    queryClick(rowData) { //查看
      this.$router.push("/device/index/detail/" + rowData.id);
    }
    editClick(rowData) { //编辑
      getDeviceDetail(rowData.id).then(response => {
        let res = response.data;
        if (res.status) {
          this.commonEdit(res.data, 2);
        } else {
          this.showMessage(res.message, 'error');
        }
      })
    }
    commonEdit(rowData, index) { //弹出表单共用方法
      this.submitIndex = index;
      this.formTitle = index === 0 ? "添加设备" : "编辑设备";
      this.disabled = index === 2 ? true : false;
      this.form = Object.assign({}, rowData);
      this.dialogVisible = true;
    }
    submitForm(deviceForm) { //表单提交方法
      this.listLoading = true
      if (this.submitIndex === 0) {
        addDevice(deviceForm).then(response => {
          this.commonSubmitRes(response.data, this.submitIndex);
        }, error => {
          this.listLoading = false;
        })
      } else {
        let updateObj = { id: deviceForm.id, desc: deviceForm.desc };
        updateDevice(updateObj).then(response => {
          this.commonSubmitRes(response.data, this.submitIndex);
        }, error => {
          this.listLoading = false;
        })
      }
    }
    commonSubmitRes(response, index) { //提示回调方法
      if (response.status) {
        let message = index === 0 ? '添加设备成功' : (index === 3 ? '删除设备成功' : '修改设备成功');
        this.showMessage(message, 'success');
        this.dialogVisible = false;
        this.pageIndex = 0;
        this.fetchData();
        this.initDeviceTotalInfo();
      } else {
        this.showMessage(response.message, 'error');
      }
      this.listLoading = false;
    }
    deleteClick(rowData) { //删除方法
      this.$msgbox.confirm('确定要删除设备：' + rowData.name + ' 吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice(rowData.id).then(response => {
          this.commonSubmitRes(response.data, 3);
        })
      })
    }
    handleSelectionChange(rowData) { //多选数组回调方法
      this.multipleSelection = rowData;
    }
    multipleSelectionChange(type) { //多选回调方法
      // console.log(this.multipleSelection);
      if (!this.multipleSelection.length) {
        this.showMessage('请先勾选需要更改状态的设备', 'warning');
        return;
      }
      let ids = this.multipleSelection.map(item => item.id);
      ids = ids.join(',');
      let deviceData = { ids: ids };
      switch (type) {
        case "delete":
          // this.multipleSelection.forEach(row => {

          // });
          this.$msgbox.confirm('确定要删除这些设备吗？', '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteDevice(ids).then(response => {
              this.commonSubmitRes(response.data, 3);
            })
          })
          break;
        case "disable":
          deviceData.status = 0;
          this.commonUpdateDeviceStatus(deviceData);
          break;
        case "enable":
          deviceData.status = 1;
          this.commonUpdateDeviceStatus(deviceData);
          break;
      }
    }
    commonUpdateDeviceStatus(deviceData) { //更改设备状态公共方法
      updateDeviceStatus(deviceData).then(response => {
        let res = response.data;
        if (res.status) {
          this.showMessage('更改设备状态成功', 'success');
          this.pageIndex = 0;
          this.fetchData();
        } else {
          this.showMessage(res.message, 'error');
        }
      })
    }
    changeSwitch(data) { //单个switch切换回调方法
      console.log(data)
    }
    searchDevice() { //搜索方法
      this.pageIndex = 0;
      this.fetchData();
    }
  }
</script>

<style lang="scss" scoped>
  @import '~@scss/theme/table.scss';
</style>
